package com.ittx.dzt.tiktok.service;

import cn.hutool.core.collection.CollectionUtil;
import com.ittx.dzt.edi.dto.PlatformApiParamDTO;
import com.ittx.dzt.edi.dto.TimeFrameDTO;
import com.ittx.dzt.sys.response.Result;
import com.ittx.dzt.sys.util.json.JacksonTool;
import com.ittx.dzt.tiktok.constant.TiktokApiConstant;
import com.ittx.dzt.tiktok.handler.AbstractTiktokByTimeApiHandler;
import com.ittx.dzt.tiktok.util.CyUtil;
import lombok.extern.slf4j.Slf4j;
import open.constant.PlatformApiConstant;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.ZoneOffset;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 取消单增量下载
 * <p>
 * cy.returnOrder.download.byTimeFrame
 * /return_refund/202309/cancellations/search （取消单查询） https://partner.tiktokshop.com/docv2/page/650ab68bc16ffe02b8f2ea41?external_id=650ab68bc16ffe02b8f2ea41#Back%20To%20Top
 * </p>
 *
 * @author gywang
 * @since 2024-07-23
 */
@Slf4j
@Service
public class TiktokCanceledReturnOrderDownloadByTimeService extends AbstractTiktokByTimeApiHandler<TimeFrameDTO> {

    private static final Integer DEFAULT_PAGE_SIZE = 50;

    private static final List<String> CANCEL_STATUS = Arrays.asList(
            "CANCELLATION_REQUEST_PENDING",
            "CANCELLATION_REQUEST_SUCCESS",
            "CANCELLATION_REQUEST_CANCEL",
            "CANCELLATION_REQUEST_COMPLETE");

    @Autowired
    private TiktokCanceledReturnOrderDownloadByIdService tiktokCanceledReturnOrderDownloadByIdService;

    @Override
    protected String getMqTopic() {
        return TiktokApiConstant.Rocket.TIKTOK_DOWNLOAD_CANCELED_LIST_BY_TIME_BATCH_SPLIT_TOPIC;
    }

    @Override
    public String getTiktokMethod() {
        return TiktokApiConstant.DOWNLOAD_CANCELED_LIST;
    }

    @Override
    public String getLocalApiMethod() {
        return PlatformApiConstant.InboundInterface.RETURNORDER_CANCEL_DOWNLOAD_BY_TIMEFRAME;
    }

    @Override
    protected Result<?> doProcessByNormalType(PlatformApiParamDTO platformApiParamDTO, TimeFrameDTO timeFrameDTO) {
        Result<?> validResult = checkShopCipherInfo(platformApiParamDTO);
        if (validResult.hasError()) {
            return validResult;
        }
        Map<String, Boolean> logMap = new HashMap<>();
        return this.requestListBySdk(platformApiParamDTO, timeFrameDTO, logMap);
    }

    @Override
    protected Result<?> doProcessByCheckType(PlatformApiParamDTO platformApiParamDTO, TimeFrameDTO timeFrameDTO) {
        Result<?> validResult = checkShopCipherInfo(platformApiParamDTO);
        if (validResult.hasError()) {
            return validResult;
        }
        // 探查成功时不返回完整数据,只返回数量
        return this.requestListBySdk(platformApiParamDTO, timeFrameDTO, null);
    }

    /**
     * rds直接批量下载后下发，不经过拆分队列
     *
     * @param platformApiParamDTO
     * @param timeFrameDTO
     * @return
     */
    @Override
    protected Result<?> doProcessByIdType(PlatformApiParamDTO platformApiParamDTO, TimeFrameDTO timeFrameDTO) {
        Result<?> validResult = checkShopCipherInfo(platformApiParamDTO);
        if (validResult.hasError()) {
            return validResult;
        }
        String refundId = platformApiParamDTO.getPlatformIdentifierTag();
        return this.asyncHandlerById(platformApiParamDTO, String.valueOf(refundId));

    }


    /**
     * sdk
     * 请求平台接口
     */
    private Result<?> requestListBySdk(PlatformApiParamDTO platformApiParamDTO, TimeFrameDTO timeFrameDTO, Map<String, Boolean> logMap) {
        Map<String, Object> params = new HashMap<>();
        params.put("shop_cipher", getShopCipher(platformApiParamDTO));
        params.put("sort_field", "update_time");
        params.put("sort_order", "DESC");
        params.put("page_size", DEFAULT_PAGE_SIZE);

        Map<String, Object> reqBody = new HashMap<>();

        reqBody.put("update_time_ge", timeFrameDTO.getFrom().toEpochSecond(ZoneOffset.of("+8")));
        reqBody.put("update_time_lt", timeFrameDTO.getTo().toEpochSecond(ZoneOffset.of("+8")));
        // 状态过滤
        List<String> statusList = CyUtil.getStatusList(platformApiParamDTO, "return");
        if (CollectionUtil.isNotEmpty(statusList)) {
            List<String> status = (List<String>) CollectionUtil.intersection(statusList, CANCEL_STATUS);
            if (CollectionUtil.isNotEmpty(status)) {
                reqBody.put("cancel_status", status);
            }
        }
        String pageToken = null;
        do {
            if (pageToken != null) {
                params.put("page_token", pageToken);
            }
            Result<?> result = this.executeTiktokApi(getDefaultUrl(platformApiParamDTO.getStoreConfig()), platformApiParamDTO.getStoreConfig(), params, JacksonTool.toJson(reqBody), platformApiParamDTO.getRequestId(), TiktokApiConstant.ApiHttpMethod.POST);
            if (!result.isSuccess()) {
                return result;
            }
            Map<String, Object> resultMap = (Map<String, Object>) result.getData();
            Map<String, Object> dataMap = (Map<String, Object>) resultMap.get(DATA_FIELD);
            // 售后单总数
            Integer total = Integer.parseInt(dataMap.get(RESULT_TOTAL).toString());
            pageToken = (String) dataMap.get("next_page_token");
            // 探查模式只返回总数
            if (PlatformApiConstant.ApiByTime.CHECK.equals(platformApiParamDTO.getQueryType())) {
                return Result.success().addData(total);
            }
            List<Map<String, Object>> list = (List<Map<String, Object>>) dataMap.get("cancellations");
            if (CollectionUtil.isNotEmpty(list)) {
                for (Map<String, Object> refund : list) {
                    String refundId = (String) refund.get("order_id");
                    sendToSplitTopic(platformApiParamDTO, refundId, logMap);
                }
            }

        } while (StringUtils.isNotBlank(pageToken));

        return Result.success(logMap);
    }

    /**
     * sdk
     * <p>
     * 根据订单号下载售后单 ------- 多线程执行
     */
    @Override
    public Result<?> asyncHandlerById(PlatformApiParamDTO platformApiParamDTO, String refundId) {
        Result<?> result = tiktokCanceledReturnOrderDownloadByIdService.getRefundById(platformApiParamDTO, refundId);
        if (!result.isSuccess()) {
            return result;
        }
        return this.sendRequestToPlatform(platformApiParamDTO, result.getData(), true);
    }
}
